#include "comm.hpp"

void getMessage(int fd)
{
    while (true)
    {
        // 读取管道文件
        char readBuffer[1024];
        memset(readBuffer, 0, sizeof(readBuffer));
        int len = read(fd, readBuffer, sizeof(readBuffer) - 1);
        if (len > 0)
        {
            std::cout << "--pipe read success!!--" << std::endl;
            std::cout << "PID[" << getpid() << "]: " << readBuffer << std::endl;
        }
        else if (len == 0)
        {
            std::cout << "--write closed!! read close!!--" << std::endl;
            break;
        }
        else
        {
            perror("pipe read:");
            break;
        }
    }
}

// 读管道信息
int main()
{
    // 创建有名管道
    int n = mkfifo(PIPE_PATH, MODE);
    assert(n != -1);
    std::cout << "--pipe create success!!--" << std::endl;

    int fd = open(PIPE_PATH, O_RDONLY); // 打开管道
    assert(fd != -1);
    std::cout << "--pipe r_open success!!--" << std::endl;

    std::vector<pid_t> pids; // 记录子进程pid
    for (size_t i = 0; i < 5; i++)
    {
        pid_t pid = fork();
        if (pid == 0)
        {
            // 子进程
            getMessage(fd);
            exit(1);
        }
        pids.push_back(pid);
    }

    // 等待子进程
    for (auto id : pids)
    {
        waitpid(id, nullptr, 0);
    }

    close(fd); // 关闭管道文件
    unlink(PIPE_PATH);

    return 0;
}